package com.maoslv.security;

import com.alibaba.fastjson.JSON;
import com.maoslv.dto.Result;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//权限不足处理器
@Component
public class MyAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        //设置响应回去的类型
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        //设置响应状态码
        httpServletResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);

        ServletOutputStream outputStream = httpServletResponse.getOutputStream();
        outputStream.write(JSON.toJSONString(Result.fail(HttpServletResponse.SC_FORBIDDEN,"限权不够")).getBytes("UTF-8"));
        outputStream.flush();
        outputStream.close();
    }
}
